package com.hoopchina.util.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.hoopchina.util.LogUtils;
import com.hoopchina.util.UrlUtils;
import com.hoopchina.util.download.DownloadTask.Type;

import android.os.Environment;

public class DownloadExecutor {
    private static final int        SAVEPATH_NOT_AVAILABLE = -1;
    private static final int        FILE_EXISTS            = -2;
    private static final int        DOWNLOAD_COMPLETE      = 0;
    private static String           mFileName              = "";

    public static void start(DownloadTask aTask, DownloadCallback aCallback ) {

        LogUtils.d(   "DownloadExecutor start() task url = " + aTask.getTargetUrl() );
        
		if (aTask.getType() == Type.XML_HOME_LIST
				|| aTask.getType() == Type.JSON_LOCAL_LIST) {

			setFileName(UrlUtils.getNameFromUrl(aTask.getNameUrl()));

		} else {
			setFileName(UrlUtils.getNameFromUrl(aTask.getTargetUrl()));
		}
		
        LogUtils.d( "fileName = " + getFileName() );
        
        try {
            File savePath = new File( aTask.getSavePath() );
            if ( checkStorable( savePath ) == false ) {
                if(aCallback != null){
                    aCallback.onFailed();
                }
                else {
                    return;
                }
            }
            File saveFile = new File( aTask.getSavePath(), getFileName() );
            if ( saveFile.exists() ) {
				LogUtils.i("FILE_EXISTS :"+saveFile.toString());
                if ( aTask.getType() == DownloadTask.Type.XML_HOME_LIST )
                    saveFile.delete();
                else {
                    if ( aCallback != null )
                        aTask.setStatus( true );
                        aCallback.onFinished( aTask );
                    return;
                }
            }
            File tmpFile = new File( aTask.getSavePath(), getFileName() + ".tmp" );
            URL reqUrl = new URL( aTask.getTargetUrl() );
            HttpURLConnection conn = ( HttpURLConnection ) reqUrl.openConnection();
            conn.setConnectTimeout( 5 * 1000 );
            conn.setRequestMethod( "GET" );
            conn.setRequestProperty( "Accept", "*/*" );
            conn.setRequestProperty( "Accept-Language", "zh-CN" );
            conn.setRequestProperty( "Charset", "UTF-8" );
            conn.connect();

            if ( conn.getResponseCode() == 200 ) {
                LogUtils.i(   "200 OK,realUrl: " + conn.getURL().toString() );
                InputStream is = conn.getInputStream();
                int length = conn.getContentLength();
                LogUtils.i(   "服务器端大小: " + length );
                if ( length != -1 ) {
                 // temp fix
                    OutputStream out = new FileOutputStream( tmpFile );
                    byte buf[] = new byte[1024];
                    int len;
                    while ( ( len = is.read( buf ) ) > 0 )
                        out.write( buf, 0, len );
                    out.close();
                    // temp fix end
                    tmpFile.renameTo( saveFile );
                    LogUtils.i(   "下载完成,重命名 为: " + saveFile );
                    is.close();
                    // task complete here
                    aTask.setStatus( true );
                    if ( aCallback != null ) {
                        aCallback.onFinished(aTask);
                    }
                }
                else {
                    LogUtils.i(   "Unkown file size" );
                    if ( aCallback != null ) {
                        aCallback.onFailed();
                    }
                    return;
//                    throw new IOException( "Unkown file size " );
                }
            }
            else {
                LogUtils.i(   "can't connect to server" );
                if ( aCallback != null ) {
                    aCallback.onFailed();
                }
                return;
//                throw new IOException( "can't connect to server " );
            }

        }
        catch ( MalformedURLException e ) {
            // caused by new URL( aUrl );
            LogUtils.e(   "MalformedURLException :" + e.toString() );
        }
        catch ( IOException e ) {
            // caused by reqUrl.openConnection();
            LogUtils.e(   "IOException :" + e.toString() );
            if ( aCallback != null ) {
                aCallback.onFailed();
            }
        }
        catch ( Exception e ) {
            LogUtils.e( "Exception :" +e.toString() +UrlUtils.getNameFromUrl( aTask.getTargetUrl() ));
        }
        
    }

    /**
     * 检查路径是否可用
     * 
     * @param aSavePath
     * @return
     * @throws IOException
     */
    private static boolean checkStorable( File aSavePath ) {
        if ( aSavePath.toString().contains( "sdcard" ) ) {
            if ( Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED ) ) {
                if ( aSavePath.exists() )
                    return true;
                else {
                    aSavePath.mkdirs();
                    return true;
                }
            }
            else {
                return false;
            }
        }

        return true;
    }

    public static void setFileName( String aFileName ) {
        mFileName = aFileName;
    }

    public static String getFileName() {
        return mFileName;
    }
}